package com.bookmngsys.dao;

import com.bookmngsys.entity.Book;
import org.springframework.data.jpa.repository.JpaRepository;
import org.springframework.data.jpa.repository.Modifying;
import org.springframework.data.jpa.repository.Query;
import org.springframework.transaction.annotation.Transactional;

import java.util.ArrayList;

/**
 * @author han
 */
public interface BookDao extends JpaRepository<Book, String> {
    @Query(value = "select * from book where status=1 LIMIT :curPage,:pageSize", nativeQuery = true)
    ArrayList<Book> findEnabledBooks(int curPage, int pageSize);

    @Query(value = "select * from book where book_name like concat('%', :bookName, '%')", nativeQuery = true)
    ArrayList<Book> searchByBookName(String bookName);

    @Query(value = "select * from book where author like concat('%', :author, '%')", nativeQuery = true)
    ArrayList<Book> searchByAuthor(String author);

    @Query(value = "select * from book where isbn like concat('%', :isbn, '%')", nativeQuery = true)
    ArrayList<Book> searchByIsbn(String isbn);

    @Query(value = "select * from book where isbn = :isbn", nativeQuery = true)
    Book findByIsbn(String isbn);

    @Transactional
    @Modifying
    @Query(value = "UPDATE Book SET lastNum=lastNum+1 WHERE isbn = :isbn and lastNum>0")
    void addBookNum(String isbn);

    @Transactional
    @Modifying
    @Query(value = "UPDATE Book SET lastNum=lastNum-1 WHERE isbn = :isbn and lastNum>0")
    void reduceBookNum(String isbn);

    @Transactional
    @Modifying
    @Query(value = "update Book set status=:status where isbn=:isbn")
    void updateBookStatus(String isbn, int status);

    @Transactional
    @Modifying
    @Query(value = "update Book set imgUrl=:url where isbn=:isbn")
    void updateBookImg(String isbn, String url);

    @Transactional
    @Modifying
    @Query(value = "UPDATE Book SET reserveNum=reserveNum+1 WHERE isbn = :isbn")
    void addBookReServeNum(String isbn);

    @Transactional
    @Modifying
    @Query(value = "UPDATE Book SET reserveNum=reserveNum-1 WHERE isbn = :isbn")
    void reduceBookReServeNum(String isbn);

}
